package com.harvest.scientific.ladder.util;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.RequestBody;

public class MapToBodyUtil {

    public static Map<String, RequestBody> getRequestBodyMap(Map<String,Object> resourceMap){
        Map<String, RequestBody> params=new HashMap<>();
        Iterator iterator=resourceMap.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry entry= (Map.Entry) iterator.next();
            if(entry.getValue() instanceof String){
                RequestBody body=RequestBody.create(MediaType.parse("text/plain;charset=UTF-8"),(String)entry.getValue());
                params.put((String)entry.getKey(),body);
            }else if(entry.getValue() instanceof File){
                RequestBody body=RequestBody.create(MediaType.parse("multipart/form-data;charset=UTF-8"),(File)entry.getValue());
                params.put((String)entry.getKey()+"\";filename=\""+((File)entry.getValue()).getName()+"",body);
            }else if(entry.getValue() instanceof File[]){
                File[] files= (File[]) entry.getValue();
                if(files != null){
                    for(File f : files){
                        RequestBody body=RequestBody.create(MediaType.parse("multipart/form-data;charset=UTF-8"),f);
                        params.put((String)entry.getKey()+"\";filename=\""+f.getName()+"",body);
                    }
                }
            }
        }
        return params;
    }
}
